#!/usr/bin/env python
# Author xiaofan <xiaofan@iscas.ac.cn>

import os
import os.path
import re

patchdir = os.path.dirname(__file__)
rootdir = os.path.join(patchdir, '..')
patchinfo = open(os.path.join(patchdir, 'patchinfo.txt'), 'r')
os.chdir(rootdir)

parse_rule = re.compile(r'(.*?)\s+(.*)')

for line in patchinfo:
    numsign_index = line.find('#')
    if numsign_index >= 0:
        line = line[:numsign_index]
    line = line.strip()
    if not line:
        continue
    m = parse_rule.match(line)
    assert(m != None)
    patchname = m.group(1)
    path = m.group(2)
    patch = os.path.join(patchdir, patchname)
    if os.path.isdir(patch):
        patches = []
        for p in os.listdir(patch):
            patch_item = os.path.join(patch, p)
            if patch_item[-6:] == '.patch' and os.path.isfile(patch_item):
                patches.append(patch_item)
        patches.sort() # do not assume os.listdir return a ordered list
    else:
        patches = [ patch ]
    if not os.path.exists(path):
        os.makedirs(path)
    for patch in patches:
        cmdline = F'patch -d {path} -p1 < {patch}'
        print(F'>>> {cmdline} ...')
        res = os.system(cmdline)
        assert(res == 0)
